/**
 * Sitemap 服务端路由
 * 从后端API获取sitemap内容并返回
 */
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const apiBase = config.public.apiBase

  try {
    // 从后端API获取sitemap
    const response = await $fetch<string>(`${apiBase.replace('/api', '')}/sitemap.xml`, {
      method: 'GET',
    })

    // 设置正确的Content-Type
    setResponseHeader(event, 'Content-Type', 'application/xml; charset=utf-8')
    setResponseHeader(event, 'Cache-Control', 'public, max-age=3600') // 缓存1小时

    return response
  } catch (error) {
    console.error('获取sitemap失败:', error)
    
    // 返回基本的sitemap
    setResponseHeader(event, 'Content-Type', 'application/xml; charset=utf-8')
    return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>${config.public.siteUrl || 'http://localhost:3000'}</loc>
    <lastmod>${new Date().toISOString().split('T')[0]}</lastmod>
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>
</urlset>`
  }
})
